﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BaseData;
using BaseData.UI;
using TaxBiz.SysConfig;
using TaxBiz.Tax;
using TaxBiz.OaSys;

namespace Admin.ALarm
{
    public partial class CreateALarm : BaseCommon.BasePage
    {
        protected static object locker = new object();
        protected int year = 0;
        protected string MailTrTemplete = "<tr><td align='center'>{'Year'}</td><td align='center'>{'DepartmentName'}</td><td align='center'>{'ManagerName'}</td><td align='center'>{'CertificateID'}</td><td align='center'>{'Name'}</td><td align='center'>{'MobileCode'}</td><td align='left' style='padding-left: 2px;'>{'RequireTax'}</td><td align='left' style='padding-left: 2px;'>{'CompleteTax'}</td><td align='right' style='padding-right: 2px;'>{'TotalTax'}</td><td align='right' style='padding-right: 2px;'>{'bTotalTax'}</td><td align='right' style='padding-right: 2px;'>{'bmsTotalTax'}</td></tr>";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!HasPower())
            {
                Jscript.AlertAndGoBack("您权限不足，不能操作");
                return;
            }
            string action = PageContext.GetRequest("action");
            year = PageContext.GetRequestInt("selYear").HasValue ? PageContext.GetRequestInt("selYear").Value : 0;
            if (!string.IsNullOrEmpty(action))
            {
                lock (locker)
                {
                    SendMail(year);
                }
            }
        }

        protected void SendMail(int year)
        {
            try
            {
                //取数据
                int pageSize = 5000;
                int page = 1;
                int allCount = 0;
                string strWhere = "";
                if (PageContext.GetRequestInt("selYear").HasValue)
                {
                    year = PageContext.GetRequestInt("selYear").Value;
                    strWhere += " and year = " + year;
                }
                DataTable dtTaxList = AlarmBiz.GetList(strWhere, pageSize, page, ref allCount);
                //发邮件（读模板填充内容）
                if (dtTaxList == null || dtTaxList.Rows.Count == 0)
                {
                    BaseData.Common.LogerHelper.WriteError(new Exception("应税计算没有数据"));
                    Jscript.AlertAndRedirect(year.ToString() + "年没有应税数据", "CreateALarm.aspx");
                    return;
                }
                StringBuilder allContent = new StringBuilder();
                using (StreamReader sr = new StreamReader(Server.MapPath("/Admin/Include/MailTemplete.htm"), System.Text.Encoding.GetEncoding("GB2312")))
                {
                    //读取每一行                
                    while (sr.Peek() >= 0)
                    {
                        allContent.Append(sr.ReadLine());
                    }
                    //所有内容                    
                    allContent.Append(sr.ReadToEnd());
                }
                StringBuilder sb = new StringBuilder();
                string atr = string.Empty;
                foreach (DataRow dr in dtTaxList.Rows)
                {
                    atr = MailTrTemplete.Replace("{'Year'}", dr["Year"].ToString());
                    atr = atr.Replace("{'DepartmentName'}", dr["DepartmentName"].ToString());
                    atr = atr.Replace("{'ManagerName'}", dr["ManagerName"].ToString());
                    atr = atr.Replace("{'CertificateID'}", dr["CertificateID"].ToString());
                    atr = atr.Replace("{'Name'}", dr["Name"].ToString());
                    atr = atr.Replace("{'MobileCode'}", dr["MobileCode"].ToString());
                    atr = atr.Replace("{'RequireTax'}", dr["RequireTax"].ToString());
                    atr = atr.Replace("{'CompleteTax'}", dr["CompleteTax"].ToString());
                    atr = atr.Replace("{'TotalTax'}", dr["TotalTax"].ToString());
                    atr = atr.Replace("{'bTotalTax'}", dr["bTotalTax"].ToString());
                    atr = atr.Replace("{'bmsTotalTax'}", (Decimal.Parse(dr["TotalTax"].ToString()) - Decimal.Parse(dr["bTotalTax"].ToString())).ToString());
                    sb.Append(atr);
                }
                allContent = allContent.Replace("<!--{content}-->", sb.ToString());
                //取收件人
                string mailTo = string.Empty;
                string mailToOaSys = string.Empty;
                DataTable dtMailTo = new TaxBiz.User.UserBiz().GetList(UserLogin.DepartmentID);
                if (dtMailTo == null || dtMailTo.Rows.Count == 0)
                {
                    Jscript.AlertAndRedirect(year.ToString() + "年没有收件人信息", "CreateALarm.aspx");
                    return;
                }
                foreach (DataRow dr in dtMailTo.Rows)
                {
                    if (dr["eMail"] != null && dr["eMail"] != DBNull.Value && !string.IsNullOrEmpty(dr["eMail"].ToString()))
                    {
                        if (dr["eMail"].ToString().ToLower().Contains("@lnds.com") || dr["eMail"].ToString().ToLower().Contains("@tax.com"))
                        {
                            dr["eMail"] = dr["eMail"].ToString().Replace("tax.com", "lnds.com");
                            mailToOaSys += dr["eMail"].ToString() + ";";
                        }
                        else
                        {
                            mailTo += dr["eMail"].ToString() + ";";
                        }
                    }
                }
                mailTo = mailTo.TrimEnd(';');
                mailToOaSys = mailToOaSys.TrimEnd(';');
                bool isSendSucc = BaseData.Common.Email.Send("出租屋税收预警通知", allContent.ToString(), mailTo);
                if (!string.IsNullOrEmpty(BaseData.UI.PageContext.GetConfig("IsOaDataInterface")) &&
                    BaseData.UI.PageContext.GetConfig("IsOaDataInterface") == "1")
                {
                    isSendSucc = EmailBiz.SendBatchByInterface(UserLogin, "出租屋税收预警通知", allContent.ToString(), mailToOaSys);
                }
                else
                {
                    isSendSucc = EmailBiz.SendBatch(UserLogin, "出租屋税收预警通知", allContent.ToString(), mailToOaSys);
                }
                TaxBiz.Log.EmailLogBiz.Add(UserLogin, mailTo + ";" + mailToOaSys, LoginDepartmentID, allContent.ToString(), isSendSucc);
                Jscript.AlertAndRedirect(year.ToString() + "年信息对比成功", "CreateALarm.aspx");
            }
            catch(Exception e)
            {
                BaseData.Common.LogerHelper.WriteError(e);
                Jscript.AlertAndRedirect(year.ToString() + "年信息对比失败", "CreateALarm.aspx");
            }
        }
    }
}